package com.lagou.config;

import com.lagou.pojo.Configuration;
import com.lagou.pojo.MapperStatement;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * XmlMapperBuilder，SQL配置文件解析类，
 *
 * @author YiYa
 * @since 2020-11-08 上午 10:03
 */
public class XmlMapperBuilder {

    private Configuration configuration;

    public XmlMapperBuilder(Configuration configuration) {
        this.configuration = configuration;
    }

    public void parse(InputStream inputStream) throws DocumentException {
        Document document = new SAXReader().read(inputStream);
        Element rootElement = document.getRootElement();
        String namespace = rootElement.attributeValue("namespace");

        List<Element> list = rootElement.selectNodes("//select");
        List<Element> insertList = rootElement.selectNodes("//insert");
        List<Element> updateList = rootElement.selectNodes("//update");
        List<Element> deleteList = rootElement.selectNodes("//delete");
        List<Object> objectList = new ArrayList<>();
        objectList.add(list);
        objectList.add(insertList);
        objectList.add(updateList);
        objectList.add(deleteList);

        /*for (Element element : list) {
            String id = element.attributeValue("id");
            String resultType = element.attributeValue("resultType");
            String parameterType = element.attributeValue("parameterType");
            String textTrim = element.getTextTrim();
            MapperStatement mapperStatement = new MapperStatement();
            mapperStatement.setId(id);
            mapperStatement.setResultType(resultType);
            mapperStatement.setParameterType(parameterType);
            mapperStatement.setSql(textTrim);
            configuration.getMapperStatementMap().put(namespace + "." + id, mapperStatement);
        }*/
        for (Object object : objectList) {
            List<Element> elements = (List<Element>) object;
            for (Element element : elements) {
                String id = element.attributeValue("id");
                String resultType = element.attributeValue("resultType");
                String parameterType = element.attributeValue("parameterType");
                String sqlText = element.getTextTrim();
                MapperStatement mapperStatement = new MapperStatement();
                mapperStatement.setId(id);
                mapperStatement.setResultType(resultType);
                mapperStatement.setParameterType(parameterType);
                mapperStatement.setSql(sqlText);
                configuration.getMapperStatementMap().put(namespace + "." + id, mapperStatement);
            }
        }
    }
}
